// 平台商品Datatable
var itemTable;
var createGroupTable;
var goodsSkuTable;
// 正在操作的“平台商品ID”
var opEcItemId = "";
var btnAdvSearchflg = false;
// 用于记录要删除的组件商品信息
var groupdelete = new Array();
var goodsSkuIdAdd = new Array();
var nEditing = null;
var map = {};// 记录原始的规格数据
var reg = /^[0-9]+$/; // 正则表达式 英数字
var cashReg = /^[0-1]+(.[0-9]{0,2})?$/;// 金额正则表达式
var projectSkuListTable;

//初始化iCheck组件
turn_on_iCheck = function(domElement) {
    return $('input[type="checkbox"],input[type="radio"]', domElement).iCheck({
        checkboxClass : 'icheckbox_flat-red',
        radioClass : 'iradio_flat-red'
    });
};

/**
 * 页面初始化
 */
$(function() {
    $("#advSearchPanel").hide();
    // 初始化店铺列表
    getShopList();
    //按钮控制
    setPageElementStatus("itemList");
    // 初始化表格控件
    goodsSkuTable = $('#goodsSkuTable').DataTable({
        "processing" : true,
        "serverSide" : true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000] ],
        "dom" : '<"bottom"rtflp>',
        "searching" : false,
        "pagingType" : "full_numbers",
        "deferRender" : true,
        "ajax" : {
            "url" : "/goods/getAllGoodsSkuList.action",
            "data": function (d) {
                if ($('#goodsSkuSearch').val() == undefined) {
                    d.quickSearch = encodeURI(window.top.window.$('#goodsSkuSearch').val());
                } else {
                    d.quickSearch = encodeURI($('#goodsSkuSearch').val());
                }
            }
        },
        "tableTools" : {
            "sRowSelect" : "bootstrap"
        },
        "columns" : [ {
            "data" : "goodsSkuIdChk"
        }, {
            "data" : "goodsCode"
        }, {
            "data" : "goodsName"
        }, {
            "data" : "skuCode"
        }, {
            "data" : "skuName"
        } ],
        "columnDefs" : [ {
            "orderable" : false,
            "targets" : [ 0 ]
        } ],
        "order" : [ [ 1, "asc" ], [ 2, "asc" ], [ 3, "asc" ], [ 4, "asc" ] ]
    });

    // 初始化表格控件
    itemTable = $('#itemTable').DataTable({
        "processing" : true,
        "serverSide" : true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000], [ 10, 25, 50, 100, 500, 1000 ] ],
        "dom" : '<"bottom"rtflp>',
        "searching" : false,
        "pagingType" : "full_numbers",
        "deferRender" : true,
        "scrollX":true,
        "scrollCollapse":true,
        "ajax" : {
            "url" : "/item/itemList.action",
            "data" : function(d) {
                // if ($("#advSearchPanel").is(":hidden")) {

                //快速查询条件
                    d.quickSearch = encodeURI($('#quickSearch').val());

                // } else {

                    // 高级查询条件
                    var shopId = $('#shopId').val();
                    var shopType = encodeURI($('#shopType').val());
                    var approveStatus = encodeURI($('#status').val());
                    var ecItemCode = encodeURI($('#ecItemCode').val());
                    var ecItemName = encodeURI($('#ecItemName').val());
                    var ecSkuCode = encodeURI($('#ecSkuCode').val());
                    var ecSkuName = encodeURI($('#ecSkuName').val());
                    var outerCode = encodeURI($('#outerCode').val());
                    var itemOuterCode = encodeURI($('#itemOuterCode').val());
                    var advData = {
                        "shopId" : shopId,
                        "shopType" : shopType,
                        "approveStatus" : approveStatus,
                        "ecItemCode" : ecItemCode,
                        "ecItemName" : ecItemName,
                        "ecSkuCode" : ecSkuCode,
                        "ecSkuName" : ecSkuName,
                        "outerCode":outerCode,
                        "itemOuterCode":itemOuterCode
                    };

                    d.formJson = JSON.stringify(advData);

                // }
            }
        },
        "tableTools" : {
            "sRowSelect" : "bootstrap"
        },
        "columns" : [ {
            "data" : "skuShow"
        }, {
            "data" : "chk"
        }, {
            "data" : "relateStatus",
            "render" : function(data, type, row, meta) {
                if (row.relateStatus == "all") {
                    return "<span title='全部关联' class='badge badge-green'> </span>";
                } else if (row.relateStatus == "part") {
                    return "<span title='部分关联' class='badge badge-orange'> </span>";
                } else {
                    return "<span title='未关联' class='badge badge-red'> </span>";
                }
            }
        }, {
            "data" : "ecItemCode"
        }, {
            "data" : "",
            "render" : function(data, type, row, meta) {
                return row.ecItemName.replace(/ /g, "&nbsp;");
            }
        }, {
            "data" : "outerCode"
        }, {
            "data" : "status"
        }, {
            "data" : "prjName"
        }, {
            "data" : "shopName"
        }, {
            "data" : "shopType"
        }, {
            "data" : "autoList",
            "render" : function(data, type, row, meta) {
                if (row.autoList == "n") {
                    return "<span class='badge badge-red'> </span>";
                } else {
                    return "<span class='badge badge-green'> </span>";
                }
            }
        }, {
            "data" : "ecItemId"
        } ],
        "columnDefs": [
            {"orderable": false, "targets":[0]},
            {"orderable": false, "targets":[1]},
            {"className": "truncate-text tooltip-column-detail-5", "targets":[2]},
            {"className": "truncate-text tooltip-column-detail-5", "targets":[3]},
            {"className": "truncate-text tooltip-column-detail", "targets":[4]},
            {"className": "truncate-text tooltip-column-detail-5", "targets":[5]},
            {"className": "truncate-text tooltip-column-detail-5", "targets":[6]},
            {"className": "truncate-text tooltip-column-detail-5", "targets":[7]},
            {"className": "truncate-text tooltip-column-detail-5", "targets":[8]},
            {"className": "truncate-text tooltip-column-detail-5", "targets":[9]},
            {"visible": false, "targets":[11]}
        ],
        "order" : [ [ 7, "asc" ], [ 9, "asc" ], [ 8, "asc" ], [ 3, "asc" ] ]
    }).on('draw.dt',  function() {
       /*turn_on_iCheck($("#itemTable_wrapper"));
        $("#chkAll").on("ifChanged", function() {
            if ($("#chkAll").is(":checked")) {
                $("#itemTable_wrapper").find(".icheck").iCheck("check");
            } else {
                $("#itemTable_wrapper").find(".icheck").iCheck("uncheck");
            }
        });*/
    });
    
    // 文字过长截断显示悬浮框
    $("#itemTable").tooltip({
        selector: ".tooltip-column-detail-5,.tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
    
    // 快速查询回车
    $('#quickSearch').keydown(function(e){
        if (e.keyCode == 13 && $('#btnQuickSearch').is(":visible")) {
            $('#btnQuickSearch').click();
        }
    });

    // 快速搜索，点击时提交表格刷新内容
    $("#btnQuickSearch").click(function() {
        itemTable.draw();
    });


    // $("body").click(function(e) {
    //     if (btnAdvSearchflg == true) {
    //         btnAdvSearchflg = false;
    //     } else {
    //         $("#advSearchPanel").hide();
    //         $("#btnAdvSearch").children("i:eq(0)").removeClass("fa-angle-double-up");
    //         $("#btnAdvSearch").children("i:eq(0)").addClass("fa-angle-double-down");
    //     }
    // });
    // 高级搜索“提交”按钮点击
    $("#advSearchSubmit").click(function(e) {
        // 记录高级查询的检索条件
        setHidValue("frmAdvSearch");

        itemTable.draw();
        // $("#advSearchPanel").hide();
        // $("#btnAdvSearch").children("i:eq(0)").removeClass("fa-angle-double-up");
        // $("#btnAdvSearch").children("i:eq(0)").addClass("fa-angle-double-down");

    });

    // 高级搜索
    $("#advSearchPanel").hide();
    $("#btnAdvSearch").click(function() {
        btnAdvSearchflg = true;
        if ($("#advSearchPanel").is(":hidden")) {
            $("#advSearchPanel").show();
            $("#btnQuickSearch").hide();
            $(this).children("i:eq(0)").removeClass("fa-angle-double-down");
            $(this).children("i:eq(0)").addClass("fa-angle-double-up");
        } else {
            $("#advSearchPanel").hide();
            $("#btnQuickSearch").show();
            $(this).children("i:eq(0)").removeClass("fa-angle-double-up");
            $(this).children("i:eq(0)").addClass("fa-angle-double-down");
        }

    });
    $("#advSearchPanel").click(function() {
        btnAdvSearchflg = true;
    })
    
    $.ajax({
        type: "GET",
        url: "/shop/unpagedShopList.action?prjId=" + window.top.window.$("#projectSwitch").val(),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data.result == "success") {
                $("#shopId_synch option").remove();
                $("#shopId_synch").append("<option value=''>请选择</option>");
                $.each(data.data, function (n, value) {
                    $('#shopId_synch').append("<option value='" + value.shopId + "'>" + value.shopName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

    /**
     * 初始化项目列表
     */
//    $.ajax({
//        type : "GET",
//        url : "/projectManager/getAllValidProjects.action",
//        contentType : "application/json;charset=utf-8",
//        dataType : "json",
//        async : false,// 同步
//        success : function(data) {
//            if (data.result == "success") {
//                $("#prjId option").remove();
//                $("#prjId").append("<option value=''>请选择</option>");
//                $.each(data.data, function(n, value) {
//                    $("#prjId").append("<option value='" + value.prjId + "'>" + value.prjName + "</option>");
//                });
//            } else {
//                window.top.window.showModalAlert(data.msg);
//            }
//        },
//        error : function(XMLHttpRequest, textStatus) {
//            if (XMLHttpRequest.status == 500) {
//                var result = eval("(" + XMLHttpRequest.responseText + ")");
//                alert(result.errorObject.errorText);
//            }
//        }
//    });

    /**
     * 获取店铺列表
     */
    function getShopList() {
        // 项目ID
        var prjId = encodeURI(encodeURI(window.top.window.$("#projectSwitch").val()));

        // 初始化店铺列表
        $.ajax({
            type : "GET",
            url : "/shop/getShopListByPrjId.action?prjId=" + prjId,
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            async : false,// 同步
            success : function(data) {
                if (data.result == "success") {
                    $("#shopId option").remove();
                    $("#shopId").append("<option value=''>请选择</option>");
                    $.each(data.data, function(n, value) {
                        $("#shopId").append("<option value='" + value.shopId + "'>" + value.shopName + "</option>");
                    });
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });

    };
    
    // 窗体大小变化时
    $(window).resize(function() {
        // 宽度
        var sonWidth = $('.portlet-body').width()-20;
        $("#sonTableDiv").width(sonWidth);
    });
    
    // 单价，金额格式化
    var numberParser = function(data){
        var returnValue = "-";
        var numberData = parseFloat(data);
        if(numberData===+numberData){
            returnValue = numberData.toFixed(2);
        }
        return returnValue;
    };

    // 子表格显示隐藏
    var tableId = "itemTable";
    var childTables = new Array();
    var tableHtml = "";
    $('#' + tableId + ' tbody').on('click', 'td .fa', function() {
        // 宽度
        var sonWidth = $('.portlet-body').width()-40;
        // 取得主键
        var ecitemid = $(this).attr('ecitemid');
        var tr = $(this).closest('tr');
        var row = itemTable.row(tr);
        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
            $(this).removeClass('fa-chevron-up');
            $(this).addClass('fa-chevron-down');
        } else {
            // 关闭其他
            $('#itemTable tbody tr').each(function() {
                if ($(this).attr("role") == "row") {
                    itemTable.row($(this)).child.hide();
                }
            });
            $('.fa-chevron-up').addClass('fa-chevron-down');
            $('.fa-chevron-down').removeClass('fa-chevron-up');
            // 生成datatable的HTML代码
            // 判断相应的id的datatable是否存在
            if ($('#itemTable' + ecitemid).length <= 0) {
                var temp = '';
                temp += '<div id="sonTableDiv" style="width:' + sonWidth + 'px">';
                temp += '<table id="itemTable' + ecitemid + '" style="width:100%"';
                temp += 'class="table table-hover table-striped table-bordered table-advanced tb-sticky-header">';
                temp += '<thead>';
                temp += '<tr>';
                temp += '<th width="10%" colValue="ecSkuCode">平台规格编码</th>';
                temp += '<th width="15%" colValue="ecSkuName">平台规格名称</th>';
                temp += '<th width="10%" colValue="outerCode">平台规格商家编码</th>';
                
                temp += '<th width="5%" colValue="outerCode">商品商家编码</th>';
                temp += '<th width="5%" colValue="outerCode">商品名称</th>';
                temp += '<th width="5%" colValue="outerCode">规格商家编码</th>';
                temp += '<th width="10%" colValue="outerCode">规格名称</th>';
                
                temp += '<th width="5%" colValue="salePrice">价格</th>';
                temp += '<th width="5%" colValue="otPrice">市场价</th>';
                temp += '<th width="5%" colValue="cost">成本价</th>';
                temp += '<th width="5%" colValue="qty">平台库存数量</th>';
                temp += '<th width="5%" colValue="autoStock">允许库存同步</th>';
                temp += '<th width="5%" colValue="isGroup">组合商品</th>';
                temp += '<th width="20%" colValue="operation">操作</th>';
                temp += '</tr>';
                temp += '</thead>';
                temp += '<tbody>';
                temp += '</tbody>';
                temp += '</table>';
                temp += '</div>';
                // Open this row
                row.child(temp).show();
                tr.addClass('shown');
                var childTable = new Object();
                childTable.id = "itemTable" + ecitemid;
                childTable.table = $('#itemTable' + ecitemid).DataTable({
                    "bPaginate": false,
                    "processing": true,
                    "serverSide": true,
                    "dom": '<"bottom"rtfli>',
                    "searching": false,
                    "deferRender": true,
                    "info": false,
                    "scrollX" : true,
                    "scrollY" : "200px",
                    "scrollCollapse": false,
                    "ajax" : {
                        "url" : "/item/skuList.action",
                        "data" : function(d) {
                            d.ecItemId = encodeURI(ecitemid);
                        }
                    },
                    "tableTools" : {
                        "sRowSelect" : "bootstrap"
                    },
                    "columns" : [ 
                        {"data" : "ecSkuCode"}, 
                        {"data" : "ecSkuName"}, 
                        {"data" : "outerCode"},
                        {"data" : "goodsCode"}, 
                        {"data" : "goodsName"},
                        {"data" : "skuCode"},
                        {"data" : "skuName"}, 
                        {"data" : "salePrice", "render": numberParser}, 
                        {"data" : "otPrice", "render": numberParser}, 
                        {"data" : "cost", "render": numberParser}, 
                        {"data" : "qty"}, 
                        {"data": "autoStock", "orderable": false,
                            "render": function ( data, type, row, meta ) {
                                var checkStr = "";
                                if (row.autoStock == "y") {
                                    checkStr = "checked";
                                }
                                return '<input ecSkuId="' + row.ecSkuId + '" type="checkbox" class="autoStockCls" ' + checkStr + ' />';
                            },
                        },
                        {"data" : "isGroupShow"}, 
                        {"data" : "operation", "orderable": false}
                    ],
                    "columnDefs": [
                        {"className": "text-right", "targets":[7]},
                        {"className": "text-right", "targets":[8]}
                    ],
                    "order" : [ [ 0, "asc" ] ]
                }).on('draw.dt',
                      function() {
                          // 设置允许库存同步
                          $(".autoStockCls").on('click',function() {
                              var autoStock = "";
                              if($(this).get(0).checked) {
                                  autoStock = "y";
                              } else {
                                  autoStock = "n";
                              }
                              var data = {"ecSkuId":$(this).attr("ecSkuId"), "autoStock":autoStock};
                              
                              $.ajax({
                                  type : "post",
                                  url : "/item/updateAutoStock.action",
                                  traditional : true,
                                  data : data,
                                  async : false, // 同步
                                  success : function(data) {
                                      if (data.result == "success") {
                                          window.top.window.showScoMessage('ok', '设置成功');
                                      } else {
                                          window.top.window.showModalAlert(data.msg);
                                      }
                                  },
                                  error : function(XMLHttpRequest, textStatus) {
                                      if (XMLHttpRequest.status == 500) {
                                          var result = eval("(" + XMLHttpRequest.responseText + ")");
                                          alert(result.errorObject.errorText);
                                      }
                                  }
                              });
                          });
                      });
            } else {
                tr.addClass('shown');
            }
            $(this).addClass('fa-chevron-up');
            $(this).removeClass('fa-chevron-down');
        }
    });

    $("#deleteGroup").click(function() {
        // CheckBox选择check
        groupdelete = new Array();
        var tableRowDeleteArray = new Array();
        var index = 1;
        window.top.window.$('input:checkbox[name=groupSelect]:checked').each(function(i) {
            if ($(this).attr("ecSkuGroupId") !== null && $(this).attr("ecSkuGroupId") !== "") {
                groupdelete.push($(this).attr("ecSkuGroupId"));
            }
            tableRowDeleteArray.push(index);
            index++;
        });
        nEditing = null;
        // 表格没有批量删除行的参数
        tableRowDeleteArray.reverse(); // 从后面往前删
        for (var i = 0; i < tableRowDeleteArray.length; i++) {
            createGroupTable.fnDeleteRow(tableRowDeleteArray[i] - 1);
        }
    });

    // 创建对话框关闭事件发生
    $('#modalCreate').on('hide.bs.modal', function() {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    })

    $('#modalCreate').on('shown.bs.modal', function() {
        createGroupTable.fnDraw();
    });

    $('#goodsGroupSelect').on('hide.bs.modal', function() {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
        var editDialog = window.top.window.borrowCustomModalDialog($("#modalCreate"));
        editDialog.modal({
            show : true,
            backdrop : 'static'
        });
        createGroupTable.fnDraw();
    })

    //
    $("#createGroup").click(function() {
        $("#goodsSkuSearch").val("");
        goodsSkuTable.draw()
        $("#chkAllGoodsSku").attr("checked", false);
        window.top.window.returnCustomModalDialog();
        var editDialog = window.top.window.borrowCustomModalDialog($("#goodsGroupSelect"));
        editDialog.modal({
            show : true,
            backdrop : 'static'
        });
    });

    $("#btnGoodsSkuAction").click(
            function() {
                var skuIdArray = new Array();
                $('input:checkbox[name=groupSelect]').each(function(i) {
                    skuIdArray.push($(this).attr("skuId"));
                });
                var errorMessage = "";
                window.top.window.$('input:checkbox[name=selectSkuId]').each(
                        function(i) {
                            if ($(this).attr("checked")) {
                                var isExsit = 0;
                                var skuId = $(this).attr("goodsskuid");
                                $.each(skuIdArray, function(n, value) {
                                    if (value == skuId) {
                                        isExsit = 1;
                                        return false;
                                    }
                                });
                                if (isExsit == 0) {
                                    goodsSkuIdAdd.push($(this).attr("goodsskuid"));
                                    createGroupTable.fnAddData([
                                            '<input id="" name="groupSelect" type="checkbox"  goodsId="' + $(this).attr("goodsId")
                                                    + '" ecSkuGroupId="" skuId="' + $(this).attr("goodsskuid") + '">',
                                            $(this).attr("goodsCode"), $(this).attr("goodsName"), $(this).attr("skuCode"),
                                            $(this).attr("skuName"), '', '', '1', '' ]);
                                    createGroupTable.fnDraw();
                                } else {
                                    errorMessage = errorMessage + "商家编码（商品）:" + $(this).attr("goodsCode") + " 商品名称:" + $(this).attr("goodsName")
                                            + " 商家编码 （规格）" + $(this).attr("skuCode") + " 规格名称:" + $(this).attr("skuName") + "\n";
                                    errorMessage = errorMessage.replace(/\n/, "<br/>");
                                }
                            }

                        });

                if (errorMessage !== "") {
                    window.top.window.showModalAlertPretty(errorMessage + "已经存在");
                }
                window.top.window.returnCustomModalDialog();
                $('#goodsGroupSelect').modal('hide');
            });

    // -------------------组合商品设置 表格可编辑 start
    $('#createGroupTable').on('click', 'td', function(e) {
        // if (deleteflg==true){
        // deleteflg=false;
        // return;
        // }
        // deleteflg=false;
        // e.preventDefault();
        var nRow = $(this).parents('tr')[0];
        if (nEditing !== null && nEditing != nRow) {
            saveRow(createGroupTable, nEditing);
            editRow(createGroupTable, nRow);
            nEditing = nRow;
        } else {
            var text = $(this).find("input");
            if (text.length <= 0) {
                editRow(createGroupTable, nRow);
            }
            nEditing = nRow;
        }
    });

    function editRow(oTable, nRow) {
        var aData = oTable.fnGetData(nRow);
        // var temp = aData[7].split("goodsSkuId=");
        // var goodsSkuId=temp[1].split(">",1);
        // goodsSkuId = goodsSkuId.toString().replace(/\"/g,"");

        var rTds = $('>td', nRow);
        // if (goodsSkuId===''){
        // rTds[0].innerHTML = '<input type="text" class="form-control
        // input-small" value="' + aData[0] + '">';
        // rTds[1].innerHTML = '<input type="text" class="form-control
        // input-small" value="' + aData[1] + '">';
        // }
        rTds[5].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[5] + '">';
        rTds[6].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[6] + '">';
        // rTds[7].innerHTML = '<input type="text" class="form-control input-small" value="1" disabled>';//' + aData[7] + '
        rTds[7].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[7] + '">';
        rTds[8].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[8] + '">';
    }

    function saveRow(oTable, nRow) {
        var rInputs = $('input', nRow);
        var aData = oTable.fnGetData(nRow);
        oTable.fnUpdate(rInputs[1].value, nRow, 5, false);
        oTable.fnUpdate(rInputs[2].value, nRow, 6, false);
        oTable.fnUpdate(rInputs[3].value, nRow, 7, false);
        oTable.fnUpdate(rInputs[4].value, nRow, 8, false);
        oTable.fnDraw();
    }
    // -------------------组合商品设置 表格可编辑 end

    $("#btnGoodsAction").click(function() {

        // //系统商品信息，其中包括商品，规格集合
        var groupSkuInfo = new Object();
        // //商品信息
        // var goods = new Object();
        // //规格集合
        var arrGroupSku = new Array();
        // var sku = new Object();
        var flg = true;
        var rowCount = 0;
        // 规格表值同步
        if (nEditing != null) {
            saveRow(createGroupTable, nEditing);
            nEditing = null;
        }

        var priceRatio = 0;
        // 规格表的数据取得
        window.top.window.$('#createGroupTable tbody tr').each(function() {

            var groupSku = new Object();
            var aData = createGroupTable.fnGetData(this);
            if (aData == null) {
                return;
            }
            rowCount++;
            var temp = aData[0].split("ecSkuGroupId=");
            var ecskugroupid = temp[1].split(" skuId=", 1);
            ecskugroupid = ecskugroupid.toString().replace(/\"/g, "");

            var temp1 = aData[0].split("skuId=");
            var goodsSkuid = temp1[1].split(">", 1);
            goodsSkuid = goodsSkuid.toString().replace(/\"/g, "");

            var temp2 = aData[0].split("goodsId=");
            var goodsId = temp2[1].split(" ecSkuGroupId=", 1);
            goodsId = goodsId.toString().replace(/\"/g, "");

            var temp3 = aData[7];
//            var goodsId = temp2[1].split(" ecSkuGroupId=", 1);
//            goodsId = goodsId.toString().replace(/\"/g, "");
            if(temp3>1 || temp3<0){
                window.top.window.showModalAlert("推送系数不能大于一！");
                flg = false;
                return;
            }
            
            if (!checkGroupSku(aData)) {
                flg = false;
                priceRatio = 1;
                return;
            }
            if (ecskugroupid == "") {
                groupSku.action = "insert";
                groupSku.skuId = goodsSkuid;
                groupSku.skuCode = aData[3];
                groupSku.skuName = aData[4];
                groupSku.goodsId = goodsId;
                groupSku.goodsCode = aData[1];
                groupSku.goodsName = aData[2];
                groupSku.num = aData[5];
                groupSku.priceRatio = aData[6];
                groupSku.upRate = aData[7];
                groupSku.remark = aData[8];
                arrGroupSku.push(groupSku);
            } else {
                var ecskugroupValue = ecskugroupid;
                
                if (ecskugroupValue !== aData[5] + "," + aData[6] + "," + aData[7] + "," + aData[8]) {
                    // groupSku.action = "update";
                    groupSku.action = "insert";
                    groupSku.ecSkuGroupId = ecskugroupValue;
                    groupSku.skuId = goodsSkuid;
                    groupSku.skuCode = aData[3];
                    groupSku.skuName = aData[4];
                    groupSku.goodsId = goodsId;
                    groupSku.goodsCode = aData[1];
                    groupSku.goodsName = aData[2];
                    groupSku.num = aData[5];
                    groupSku.priceRatio = aData[6];
                    groupSku.upRate = aData[7];
                    groupSku.remark = aData[8];
                    arrGroupSku.push(groupSku);
                }
                delete map[ecskugroupid];
            }
            priceRatio = priceRatio + Number(aData[6]);

        });
        var length = window.top.window.$('#createGroupTable tbody tr').length;
        var tblText = window.top.window.$('#createGroupTable tbody tr')[0].innerText;

        if (!flg) {
            return;
        }
        if(length>0 && tblText != "表中数据为空"){
            if (priceRatio != 1) {
                window.top.window.showModalAlert("价格系数总和必须等于1");
                flg = false;
                return;
            }
        }

        $.each(map, function(key, values) {
            var groupSku = new Object();
            groupSku.action = "delete";
            groupSku.ecSkuGroupId = key;
            arrGroupSku.push(groupSku);
        });

        if (arrGroupSku.length == 0) {
            window.top.window.showModalAlert("没有需要更新的数据。");
            return;
        }

        groupSkuInfo.arrGroupSku = arrGroupSku;
        groupSkuInfo.ecSkuId = window.top.window.$("#ecSkuId").val();
        groupSkuInfo.ecItemId = window.top.window.$("#ecItemId").val();
        window.top.window.returnCustomModalDialog();
        // 父窗体归还本页的编辑对话框
        // 后台交互
        $.ajax({
            type : "POST",
            url : "/item/updateGroupGoods.action",
            data : JSON.stringify(groupSkuInfo),
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            async : false, // 同步
            success : function(data) {
                if (data.success == "y") {
                    $('#modalCreate').modal('hide');
                    itemTable.draw();
                } else {
                    window.top.window.showModalAlert(data.errormessage);
                    var editDialog = window.top.window.borrowCustomModalDialog($("#modalCreate"));
                    editDialog.modal({
                        show : true,
                        backdrop : 'static'
                    });
                }

            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });
    });

    function checkGroupSku(aData) {
        var num = aData[5];
        if (num == null || num == undefined || $.trim(num) == '') {
            window.top.window.showModalAlert("数量为空");
            return false;
        }

        if (num.length > 11) {
            window.top.window.showModalAlert("数量太大");
            return false;
        }

        if (!reg.test(num)) {
            window.top.window.showModalAlert("数量请输入大于等一的正整数");
            return false;
        }

        if (num <= 0) {
            window.top.window.showModalAlert("数量请输入大于等一的正整数");
            return false;
        }

        var priceRatio = aData[6];
        if (priceRatio == null || priceRatio == undefined || $.trim(priceRatio) == '') {
            window.top.window.showModalAlert("价格系数为空");
            return false;
        }

        if (priceRatio.length > 12) {
            window.top.window.showModalAlert("价格系数超过12位输入");
            return false;
        }

        if (!cashReg.test(priceRatio)) {
            window.top.window.showModalAlert("价格系数总和必须等于1");
            return false;
        }

        var upRate = aData[7];
        if (upRate == null || upRate == undefined || $.trim(upRate) == '') {
            window.top.window.showModalAlert("推送系数为空");
            return false;
        }

        if (upRate.length > 12) {
            window.top.window.showModalAlert("推送系数超过12位输入");
            return false;
        }

        if (!cashReg.test(upRate)) {
            window.top.window.showModalAlert("推送系数非两位小数的正实数，并且小于等于1");
            return false;
        }

        var remark = aData[8];
        if (remark !== null && remark !== undefined && $.trim(remark) !== '' && remark.length > 400) {
            window.top.window.showModalAlert("备注超过400位输入");
            return false;
        }

        return true;
    }
    
});

/**
 * 平台商品导出
 */
function exportItemList() {
//    // 平台规格列名称
    var objRelateStatus = new Object();
    objRelateStatus.name = "关联状态";  //转换
    objRelateStatus.value = "relateStatus";
    var objEcItemCode = new Object();
    objEcItemCode.name = "平台商品编码";
    objEcItemCode.value = "ecItemCode";
    var objEcItemName = new Object();
    objEcItemName.name = "平台商品名称";
    objEcItemName.value = "ecItemName";
    var objOuterCode = new Object();
    objOuterCode.name = "平台商品商家编码";
    objOuterCode.value = "outerCode";
    var objStatus = new Object(); //转换
    objStatus.name = "上下架状态";
    objStatus.value = "approveStatus";
    var objPrjName = new Object();
    objPrjName.name = "所属项目";
    objPrjName.value = "prjName";
    var objShopName = new Object();
    objShopName.name = "所属店铺";
    objShopName.value = "shopName";
    var objShopType = new Object();
    objShopType.name = "来源平台";
    objShopType.value = "shopType";
    var objAutoList = new Object();
    objAutoList.name = "自动上架";
    objAutoList.value = "autoDelist";
    
    var objEcSkuCode = new Object();
    objEcSkuCode.name = "平台规格编码";
    objEcSkuCode.value = "ecSkuCode";
    var objEcSkuName = new Object();
    objEcSkuName.name = "平台规格名称";
    objEcSkuName.value = "ecSkuName";
    var objSkuOuterCode = new Object();  //转换
    objSkuOuterCode.name = "平台规格商家编码";
    objSkuOuterCode.value = "skuOuterCode";
    var objGoodsName = new Object();
    objGoodsName.name = "商品名称";
    objGoodsName.value = "goodsName";
    var objGoodsCode = new Object();
    objGoodsCode.name = "商品商家编码";
    objGoodsCode.value = "goodsCode";
    var objSkuName = new Object();
    objSkuName.name = "规格名称";
    objSkuName.value = "skuName";
    var objSkuCode = new Object();
    objSkuCode.name = "规格商家编码";
    objSkuCode.value = "skuCode";
    var objSalePrice = new Object();
    objSalePrice.name = "价格";
    objSalePrice.value = "salePrice";
    var objoOtPrice = new Object();
    objoOtPrice.name = "市场价";
    objoOtPrice.value = "otPrice";
    var objCost = new Object();
    objCost.name = "成本价";
    objCost.value = "cost";
    var objQty = new Object();
    objQty.name = "平台库存数量";
    objQty.value = "qty";
    var objAutoStock = new Object();//转换
    objAutoStock.name = "允许库存同步";
    objAutoStock.value = "autoStock";
    var objIsGroup = new Object();
    objIsGroup.name = "组合商品";
    objIsGroup.value = "isGroup";
    
//    var objEcSkuCode = new Object();
//    objEcSkuCode.name = "平台规格编码";
//    objEcSkuCode.value = "ecSkuCode";
//    var objEcSkuName = new Object();
//    objEcSkuName.name = "平台规格名称";
//    objEcSkuName.value = "ecSkuName";
//    var objSalePrice = new Object();
//    objSalePrice.name = "价格";
//    objSalePrice.value = "salePrice";
//    var objQty = new Object();
//    objQty.name = "平台库存数量";
//    objQty.value = "qty";

    var obList = [ objRelateStatus, objEcItemCode, objEcItemName, objOuterCode, objStatus, objPrjName, objShopName, objShopType, objAutoList, objEcSkuCode, objEcSkuName, objSkuOuterCode, objGoodsName, objGoodsCode, objSkuName, objSkuCode, objSalePrice, objoOtPrice,objCost,objQty, objAutoStock, objIsGroup ];
    extraFieldJson = JSON.stringify(obList);

    //exportList('itemTable', '/item/exportCheck.action', '/item/export.action', 'exportSelectItem', '平台商品导出', 'frmAdvSearch', extraFieldJson);
    //导出调整，王兴改 2017/12/22
    exportList('', '/item/exportCheck.action', '/item/export.action', 'exportSelectItem', '平台商品导出', 'frmAdvSearch', extraFieldJson);
}

// 自动关联系统商品
function autoRelationSysGoods() {
    var checkFlg = false;
    $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
        checkFlg = true;
        return false;
    });
    
    if (!checkFlg) {
        window.top.window.showModalAlert("请选择商品");
        return;
    }
    
    window.top.window.showModalConfirm("确认要关联系统商品吗？", relationSysGoodsForConfirm);
}

// 自动关联系统商品
function relationSysGoodsForConfirm() {
    var ecitemid = new Array();

    // CheckBox选择check
    $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
        var val = $(this).attr("ecitemid");
        ecitemid.push(val);
    });

    var xval = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "post",
        url : "/item/autoRelationSysGoods.action",
        traditional : true,
        data : {
            ecitemid : ecitemid
        },
        beforeSend:function(){
            if(xval) {
                xval.settext("关联系统商品中......");
            }
        },
        async : true, // 异步
        success : function(data) {
            xval.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '关联成功');
            } else {
                var regs = new RegExp(/\\n/,"g");
                window.top.window.showModalAlertPretty(data.msg.replace(regs, "<br/>"));
            }
            itemTable.draw();
            $("#chkAll").attr("checked", false);
        },
        error : function(XMLHttpRequest, textStatus) {
            xval.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 取消关联商品点击
function cancelRelationSysGoods() {
    var checkFlg = false;
    // CheckBox选择check
    $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
        checkFlg = true;
        return false;
    });
     
    if (!checkFlg) {
        window.top.window.showModalAlert("请选择商品");
        return;
    }
     
    window.top.window.showModalConfirm("提示：取消关联，平台商品所在订单将无法审单、无法发货，无法进行库存同步到平台等后果，确认要取消吗？", cancelRelationSysGoodsForConfirm);
}

// 取消关联弹框方法
function cancelRelationSysGoodsForConfirm() {
    var ecitemid = new Array();

    // CheckBox选择check
    $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
        var val = $(this).attr("ecitemid");
        ecitemid.push(val);
    });

    var xval = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "post",
        url : "/item/batchancelRelCationSysGoods.action",
        traditional : true,
        data : {
            ecitemid : ecitemid
        },
        beforeSend:function(){
            if(xval) {
                xval.settext("取消关联系统商品中......");
            }
        },
        async : true, // 异步
        success : function(data) {
            xval.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', data.msg);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
            itemTable.draw();
            $("#chkAll").attr("checked", false);
        },
        error : function(XMLHttpRequest, textStatus) {
            xval.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 全选，全不选
var checkboxes = document.getElementsByName('chkItem');
$("#chkAll").click(function() {
    for (var i = 0; i < checkboxes.length; i++) {
        var checkbox = checkboxes[i];
        if (!$(this).get(0).checked) {
            checkbox.checked = false;
        } else {
            checkbox.checked = true;
        }
    }
});

// 全选，全不选
$("#chkAllGoodsSku").click(function() {
    var checkboxesSelectSkuId = window.top.window.document.getElementsByName('selectSkuId');
    for (var i = 0; i < checkboxesSelectSkuId.length; i++) {
        var checkbox = checkboxesSelectSkuId[i];
        if (!$(this).get(0).checked) {
            checkbox.checked = false;
        } else {
            checkbox.checked = true;
        }
    }
});

// 全选，全不选
$("#chkAllGroup").click(function() {
    var checkboxesGroupSelect = window.top.window.document.getElementsByName('groupSelect');
    for (var i = 0; i < checkboxesGroupSelect.length; i++) {
        var checkbox = checkboxesGroupSelect[i];
        if (!$(this).get(0).checked) {
            checkbox.checked = false;
        } else {
            checkbox.checked = true;
        }
    }
});

// ----------------------------------------组合商品------------------------------------------------
/**
 * 组合商品
 * 
 * @param btnEdit
 * @returns
 */
function operationGroupRelation(btnGroup) {
    var ecSkuId = $(btnGroup).attr("ecSkuId");
    var ecSkuCode = $(btnGroup).attr("ecSkuCode");
    var ecSkuName = $(btnGroup).attr("ecSkuName");
    var ecItemId = $(btnGroup).attr("ecItemId");

    nEditing = null;
    $("#createGroupLable").html("请设置平台规格商品<font style='color:red'>" + ecSkuCode + "-" + ecSkuName + "</font>的组合商品明细：");
    $("#ecSkuId").val(ecSkuId);
    $("#ecItemId").val(ecItemId)
    createGroupDivShow(ecSkuId);
    createGroupTable.fnDraw();
    $("#chkAllGroup").attr("checked", false);
    var editDialog = window.top.window.borrowCustomModalDialog($("#modalCreate"));
    editDialog.modal({
        show : true,
        backdrop : 'static'
    });
}

function createGroupDivShow(ecSkuId) {
    $('#createGroupTable').dataTable().fnClearTable();
    // 规格新规列表
    createGroupTable = $('#createGroupTable').dataTable({
        "bPaginate" : false,
        "bAutoWidth" : true,
        "bScrollAutoCss" : false,
        "sScrollY" : '200px',
        "bSort" : false,
        "searching" : false,
        "bDeferRender" : true,
        "bDestroy" : true,
        "dom" : '<"bottom"rtflp>'
    });
    groupdelete = new Array();

    // 后台ajax
    $.ajax({
        type : "GET",
        url : "/item/getGroupByEcSkuId.action?ecSkuId=" + ecSkuId,
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        async : true,// 同步
        success : function(data) {
            if (data.result == "success") {
                // 设置组合商品的列表
                $.each(data.ecSkuGroupList, function(n, value) {
                    createGroupTable.fnAddData([
                            '<input id="" name="groupSelect" type="checkbox"  goodsId="' + value.goodsId + '" ecSkuGroupId="'
                                    + value.ecSkuGroupId + '" skuId="' + value.skuId + '">', value.goodsCode, value.goodsName, value.skuCode,
                            value.skuName, value.num, value.priceRatio, value.upRate, value.remark ])
                    createGroupTable.fnDraw();
                    map[value.ecSkuGroupId] = value.num + "," + value.priceRatio + "," + value.upRate + "," + value.remark;
                });

            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

}

// 快速搜索
var operationRelationFlg = false;
$("#btnQuickSkuSearch").click(function() {
    if (window.top.window.$('#quickSkuSearch').val().trim() == "") {
        window.top.window.showModalAlert("请选择一个检索条件");
        return;
    }
    
    if (operationRelationFlg) {
        projectSkuListTable.ajax.reload();
        return;
    }

    projectSkuListTable = window.top.window.$('#tblProjectSkuList').DataTable({
        "paging" : false,
        "processing" : true,
        "serverSide" : true,
        "dom" : '<"bottom"rtflp>',
        "searching" : false,
        "scrollX" : "100%",
        "scrollY" : "200px",
        "scrollCollapse": false,
        "deferRender" : true,
        "ajax" : {
            "url" : "/item/getProjectSkuList.action",
            "dataFilter" : function(data) {
                var array = jQuery.parseJSON(data);
                return JSON.stringify({
                    data : array,
                    recordsTotal : array.length,
                    recordsFiltered : array.length
                });
            },
            "data" : function(d) {
                d.quickSkuSearch = encodeURI(window.top.window.$('#quickSkuSearch').val());
            }
        },
        "fnDrawCallback" : function(oSettings) {
            window.top.window.$("#thProjectSkuList").removeClass("sorting_asc");
        },
        "tableTools" : {
            "sRowSelect" : "bootstrap"
        },
        "columns" : [ {
            "data" : "prjSkuId",
            "render" : function(data, type, row, meta) {
                return '<input name="prjSkuIdRadio" type="radio" value="' + row.prjSkuId + '" />';
            },
            "searchable" : false,
            "orderable" : false
        }, {
            "data" : "goodsCode",
            "searchable" : false,
            "orderable" : false
        }, {
            "data" : "goodsName",
            "searchable" : false,
            "orderable" : false
        }, {
            "data" : "skuCode",
            "searchable" : false,
            "orderable" : false
        }, {
            "data" : "skuName",
            "searchable" : false,
            "orderable" : false
        } ]
    });

    operationRelationFlg = true;
});

// 搜索框的回车事件
$('#quickSkuSearch').keydown(function(e) {
    if (e.keyCode == 13) {
        window.top.window.$("#btnQuickSkuSearch").click();
    }
});

$('#frmProjectSkuList').on('hidden.bs.modal', function() {
    $("#projectSkuListForm")[0].reset();
    $("#tblProjectSkuList").find("tbody").html("");
});

$('#frmProjectSkuList').on('hide.bs.modal', function() {
    window.top.window.returnCustomModalDialog();
})

// 取消关联系统商品
function operationCancelRelation(btnCancelRelation) {
    var ecSkuId = $(btnCancelRelation).attr("ecSkuId");
    window.top.window.showModalConfirm("提示：取消关联，平台商品所在订单将无法审单、无法发货，无法进行库存同步到平台等后果，确认要取消吗？", function() {
        $.ajax({
            type : "post",
            url : "/item/cancelRelationSysGoods.action",
            traditional : true,
            data : {
                ecSkuId : ecSkuId
            },
            async : false, // 同步
            success : function(data) {
                if (data.result == "success") {
                    window.top.window.showScoMessage('ok', '取消关联成功');
                    itemTable.draw();
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });
    });
}

// 弹出关联系统商品对话框
function operationRelation(btnRelation) {
    $('#ec_sku_id').val($(btnRelation).attr("ecSkuId"));
    var ecSkuCode = $(btnRelation).attr("ecSkuCode");
    $('#skuCodeTxt').html("平台规格" + ecSkuCode);
    
    window.top.window.returnCustomModalDialog();

    var selDialog = window.top.window.borrowCustomModalDialog($("#frmProjectSkuList"));
    selDialog.modal({
        show : true,
        backdrop : 'static'
    });
    $('#frmProjectSkuList').modal('show');
}

$("#synchForm").validate({
    debug:true,
    errorPlacement: function(error, element)
    {
        error.insertAfter(element);
    }
});

// 弹出同步库存对话框
function synchStock(btnSynchStock) {
    $("#shopSynch").get(0).checked = true;
    $("#shopId_synch").val("");
    $("#shopId_synch").attr("disabled", false);
    
    var synchDialog = window.top.window.borrowCustomModalDialog($("#frmSynchStock"));
    synchDialog.modal({show:true, backdrop:'static'});

    $('#frmSynchStock').modal('show');
}

// 关闭同步库存对话框
$('#frmSynchStock').on('hidden.bs.modal', function () {
    $("#synchForm")[0].reset();
});

// 关闭同步库存对话框
$('#frmSynchStock').on('hide.bs.modal', function () {
    window.top.window.returnCustomModalDialog();
    $("#synchForm").validate().clear();
});

// 单击同步方式
$(".stockSynchCls").click(function() {
    if (window.top.window.$("#shopSynch").get(0).checked) {
        window.top.window.$("#shopId_synch").attr("disabled", false);
    } else {
        window.top.window.$("#shopId_synch").val("");
        window.top.window.$("#shopId_synch").attr("disabled", true); 
    }
});

// 库存同步
$("#btnSynch").click(function() {
    // 店铺库存同步校验
    if(window.top.window.$("#shopSynch").get(0).checked && window.top.window.$("#shopId_synch").val()=="") {
        window.top.window.showModalAlert("店铺不能为空");
        return;
    }
    
    // 商品库存同步校验
    var selectedEcItemId = new Array();
    var shopId = "";
    var diffShopFlg = false;
    if(window.top.window.$("#itemSynch").get(0).checked) {
        $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
            var val = $(this).attr("ecitemid");
            selectedEcItemId.push(val);
            
            var tempShopId = $(this).attr("shopId");
            if (shopId == "") {
                shopId = tempShopId;
            }
            if (tempShopId != shopId) {
                diffShopFlg = true;
                return false;
            }
        });
        if (selectedEcItemId.length == 0) {
            window.top.window.showModalAlert("请选中一条数据");
            return;
        }
        if (diffShopFlg) {
            window.top.window.showModalAlert("请选择同一个店铺的商品");
            return;
        }
    }
    
    window.top.window.returnCustomModalDialog();
    
    var url = null;
    var data = null;
    if ($("#shopSynch").get(0).checked) {
        url = "/item/synchShopStock.action";
        data = {"shopId": $("#shopId_synch").val()};
    } else {
        url = "/item/synchItemStock.action";
        data = {"ecItemId": selectedEcItemId};
    }
    
    var synchForm = window.top.window.borrowCustomModalDialog($("#frmSynchStock"));
    synchForm.modal('hide');
    var xval = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "post",
        url : url,
        traditional : true,
        data : data,
        async : true, // 异步
        beforeSend:function(){
            if(xval) {
                xval.settext("库存同步中......");
            }
        },
        success : function(data) {
            xval.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '同步库存成功');
            } else {
                var reg = new RegExp(/\\n/,"g");
                window.top.window.showModalAlertPretty(data.msg.replace(reg, "<br/>"));
            }
            itemTable.draw();
            $("#chkAll").attr("checked", false);
        },
        error : function(XMLHttpRequest, textStatus) {
            xval.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
});

// SKU库存同步
function operationSynchStock(btnSynchStock) {
    var ecSkuId = $(btnSynchStock).attr("ecSkuId");
    
    $.ajax({
        type : "post",
        url : "/item/synchSkuStock.action",
        traditional : true,
        data : {
            ecSkuId : ecSkuId
        },
        async : false, // 同步
        success : function(data) {
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '同步库存成功');
                itemTable.draw();
            } else {
                var reg = new RegExp(/\\n/,"g");
                window.top.window.showModalAlertPretty(data.msg.replace(reg, "<br/>"));
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 手动设置关联商品
var skuIdForOrder;
var projectIdForOrder;
$("#btnSave_s").click(function() {
    var prjSkuId = null;
    window.top.window.$("#tblProjectSkuList tbody input[type='radio']:checked").each(function(k, v) {
        prjSkuId = this.value;
    });
    if (prjSkuId == null) {
        return window.top.window.showModalAlert("请选中一条数据");
    }
    var ecSkuId = $('#ec_sku_id').val();
    var questionFlg = "n";
    var qmsg = "";
    $.ajax({
        url : "/item/manualRelationSysGoods.action",
        type : "post",
        async : false, // 同步
        traditional : true,
        data : {
            ecSkuId : $('#ec_sku_id').val(),
            prjSkuId : prjSkuId
        },
        success : function(data) {
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '关联成功');
                window.top.window.returnCustomModalDialog();
                $('#frmProjectSkuList').modal('hide');
                itemTable.draw();
            } else if (data.result == "question") {
                // window.top.window.returnCustomModalDialog();
                qmsg = data.msg;
                questionFlg = "y";

                skuIdForOrder = ecSkuId;
                projectIdForOrder = prjSkuId;
                window.top.window.showModalConfirm(qmsg, doUpdateOrder);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
});

function doUpdateOrder(event) {
    window.top.window.returnCustomModalDialog();
    $.ajax({
        url : "/item/doUpdateOrder.action",
        type : "post",
        traditional : true,
        data : {
            ecSkuId : skuIdForOrder,
            prjSkuId : projectIdForOrder
        },
        success : function(data) {
            if (data.result == "success") {
                itemTable.draw();
                var selDialog = window.top.window.borrowCustomModalDialog($("#frmProjectSkuList"));
                selDialog.modal('hide');
                window.top.window.showScoMessage('ok', '关联系统商品成功');
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
}

/**
 * 批量设置(自动上架，自动下架)
 * 
 * @param opFlag
 *            true:自动上架， false:自动下架
 * @returns
 */
function batchSetting(opFlag) {
    var selectedEcItemId = new Array();

    $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
        var val = $(this).attr("ecitemid");
        selectedEcItemId.push(val);
    });

    if (selectedEcItemId.length == 0) {
        window.top.window.showModalAlert("请选择平台商品");
        return;
    }

    var xval = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "post",
        url : "/item/batchSetting.action",
        traditional : true,
        data : {
            selectedEcItemId : selectedEcItemId,
            opFlag : opFlag
        },
        beforeSend:function(){
            if(xval) {
                if (opFlag) {
                    xval.settext("允许自动上架中......");
                } else {
                    xval.settext("不允许自动上架中......");
                }
            }
        },
        success : function(data) {
            xval.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '批量设置成功'); 
            } else {
                window.top.window.showModalAlert(data.msg);
            }
            itemTable.draw();
            $("#chkAll").attr("checked", false);
        },
        error : function(XMLHttpRequest, textStatus) {
            xval.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

}

/**
 * 允许库存同步(允许，自动不允许)
 * 
 * @param opFlag true:允许，false:不允许
 */
function batchUpdateAutoStock(opFlag) {
    var selectedEcItemId = new Array();

    $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
        var val = $(this).attr("ecitemid");
        selectedEcItemId.push(val);
    });

    if (selectedEcItemId.length == 0) {
        window.top.window.showModalAlert("请选择平台商品");
        return;
    }

    var xval = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "post",
        url : "/item/batchUpdateAutoStock.action",
        traditional : true,
        data : {
            selectedEcItemId : selectedEcItemId,
            opFlag : opFlag
        },
        beforeSend:function(){
            if(xval) {
                if (opFlag) {
                    xval.settext("允许库存同步中......");
                } else {
                    xval.settext("不允许库存同步中......");
                }
            }
        },
        async : true, // 异步
        success : function(data) {
            xval.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '批量设置成功');
            } else {
                window.top.window.showModalAlert(data.msg);
            }
            itemTable.draw();
            $("#chkAll").attr("checked", false);
        },
        error : function(XMLHttpRequest, textStatus) {
            xval.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 商品上下架
function listingItem(listingFlg) {
    var ecitemid = new Array();

    $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
        var val = $(this).attr("ecitemid");
        ecitemid.push(val);
    });

    if (ecitemid.length == 0) {
        return window.top.window.showModalAlert("请选中一条数据");
    }

    var xval = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "post",
        url : "/item/listingItem.action",
        traditional : true,
        data : {
            ecitemid : ecitemid,
            listingFlg : listingFlg
        },
        beforeSend:function(){
            if(xval) {
                if (listingFlg) {
                    xval.settext("商品上架中......");
                } else {
                    xval.settext("商品下架中......");   
                }
            }
        },
        async : true, // 异步
        success : function(data) {
            xval.remove();
            if (data.result == "success") {
                if (listingFlg) {
                    window.top.window.showScoMessage('ok', '商品上架成功')
                } else {
                    window.top.window.showScoMessage('ok', '商品下架成功')
                }
            } else {
                var regs = new RegExp(/\\n/,"g");
                window.top.window.showModalAlertPretty(data.msg.replace(regs, "<br/>"));
            }
            itemTable.draw();
            $("#chkAll").attr("checked", false);
        },
        error : function(XMLHttpRequest, textStatus) {
            xval.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

/**
 * 将平台商品复制到系统商品
 * 
 * @returns
 */
function copyPlatformItem2SystemItem() {
    var ecitemid = new Array();

    $("#itemTable").find("tbody input[name='chkItem']:checked").each(function() {
        var val = $(this).attr("ecitemid");
        ecitemid.push(val);
    });

    if (ecitemid.length == 0) {
        return window.top.window.showModalAlert("请选中一条数据");
    }

    var xval = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "post",
        url : "/item/copyPlatformItem2SystemItem.action",
        traditional : true,
        data : {
            ecItemIds : ecitemid
        },
        beforeSend:function(){
            if(xval) {
                xval.settext("添加到系统商品中......");
            }
        },
        async : true, // 异步
        success : function(data) {
            xval.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage("ok", data.msg);
            } else {
                var regs = new RegExp(/\\n/,"g");
                window.top.window.showModalAlertPretty(data.msg.replace(regs, "<br/>"));
            }
            itemTable.draw();
            $("#chkAll").attr("checked", false);
        },
        error : function(XMLHttpRequest, textStatus) {
            xval.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 查询组合商品列表
$("#btnQuickGoodsSkuSearch").click(function () {
    goodsSkuTable.draw();
});
